//==============================================================================
// 21AT-WebGIS平台客户端程序，版权所有，二十一世纪空间技术应用股份有限公司，2000-2009。
// 作者：21AT-WebGIS平台开发组 
// 修改：	 
// 文件名：Tools.js  
// 功能：简易地图工具控件
// 最后修改时间：	2009-05-04
//==============================================================================

//================================================
//tools:interact with map 
//================================================

/**
 * Class: OpenLayers.Control.RectZoomIn 拉框放大控件
 * 
 * 继承自: - <OpenLayers.Control.ZoomBox>
 */
/**
 * @requires OpenLayers/Control/ZoomBox.js
 * @requires OpenLayers/Control/Navigation.js
 * @requires OpenLayers/Control/Button.js
 */
OpenLayers.Control.ZoomIn.prototype.title = "放大";
OpenLayers.Control.ZoomOut.prototype.title = "缩小";
OpenLayers.Control.ZoomToMaxExtent.prototype.title = "全图";

OpenLayers.Control.RectZoomIn = OpenLayers.Class(OpenLayers.Control.ZoomBox, {
	/**
	 * 工具按钮提示文字
	 * @property title
	 * @type {String}
	 */
	title : '拉框放大',

	/**
	 * 控件被触发时设置鼠标手势
	 * @method activate
	 */
	activate : function() {
		OpenLayers.Control.ZoomBox.prototype.activate.apply(this, arguments);
		this.map.layerContainerDiv.style.cursor = "url("+OpenLayers.Util.getRootPath() + "img/ZoomIn.cur),default";
	},

	/**
	 * The destroy method is used to perform any clean up before
	 * the control is dereferenced. Typically this is where event listeners are
	 * removed to prevent memory leaks.
	 * @method destroy
	 */
	destroy : function() {
		if (this.events) {
			if (this.eventListeners) {
				this.events.un(this.eventListeners);
			}
			this.events.destroy();
			this.events = null;
		}
		this.eventListeners = null;

		// eliminate circular references
		if (this.handler) {
			this.handler.deactivate();
			this.handler.destroy();
			this.handler = null;
		}
		if (this.handlers) {
			for ( var key in this.handlers) {
				if (this.handlers.hasOwnProperty(key)
						&& typeof this.handlers[key].destroy == "function") {
					this.handlers[key].destroy();
				}
			}
			this.handlers = null;
		}
		if (this.map) {
			this.map.removeControl(this);
			this.map = null;
		}
	},
	
	/**
	 * 类名称
	 * @property CLASS_NAME
	 * @type {String}
	 */
	CLASS_NAME : "OpenLayers.Control.RectZoomIn"
});

/**
 * 拉框缩小控件
 * @class OpenLayers.Control.RectZoomOut
 * @extends <OpenLayers.Control.ZoomBox>
 */
OpenLayers.Control.RectZoomOut = OpenLayers.Class(OpenLayers.Control.ZoomBox, {
	/**
	 * 工具按钮提示文字
	 * @property title
	 * @type {String}
	 */
	title : '拉框缩小',
	/**
	 * 是否为缩小，默认为缩小
	 * @property out
	 * @type {String}
	 */
	out : true,

	/**
	 * 控件被触发时设置鼠标手势
	 * @method activate
	 */
	activate : function() {
		OpenLayers.Control.ZoomBox.prototype.activate.apply(this, arguments);
		this.map.layerContainerDiv.style.cursor = "url("+OpenLayers.Util.getRootPath() + "img/ZoomOut.cur),default";
	},

	/**
	 * The destroy method is used to perform any clean up before
	 * the control is dereferenced. Typically this is where event listeners are
	 * removed to prevent memory leaks.
	 * @method destroy
	 */
	destroy : function() {
		if (this.events) {
			if (this.eventListeners) {
				this.events.un(this.eventListeners);
			}
			this.events.destroy();
			this.events = null;
		}
		this.eventListeners = null;

		// eliminate circular references
		if (this.handler) {
			this.handler.deactivate();
			this.handler.destroy();
			this.handler = null;
		}
		if (this.handlers) {
			for ( var key in this.handlers) {
				if (this.handlers.hasOwnProperty(key)
						&& typeof this.handlers[key].destroy == "function") {
					this.handlers[key].destroy();
				}
			}
			this.handlers = null;
		}
		if (this.map) {
			this.map.removeControl(this);
			this.map = null;
		}
	},
	
	/**
	 * 类名称
	 * @property CLASS_NAME
	 * @type {String}
	 */
	CLASS_NAME : "OpenLayers.Control.RectZoomOut"
});

/**
 * 平移控件
 * @class OpenLayers.Control.DragPan
 * @extends <OpenLayers.Control>
 */
OpenLayers.Control.DragPanControl = OpenLayers.Class(OpenLayers.Control.Navigation,{
	/**
	 * Property: pointQuery 实现鼠标直接点击查询
	 * {OpenLayers.Control.PointQuery}
	 */
	pointQuery : null,

	/**
	 * Property: type {String} 工具类型
	 */
	type : OpenLayers.Control.TYPE_TOOL,

	/**
	 * Property: title {String} 工具按钮提示文字
	 */
	title : '平移',

	/**
	 * Property: hoverActive {Boolean}
	 */
	// hoverActive: false,
	poiHover : null,
	/**
	 * Method: activate
	 */
	activate : function() {
		this.map.labelLayer?this.map.labelLayer.clear(): false;
		this.dragPan.activate();
		if (this.zoomWheelEnabled) {
			this.handlers.wheel.activate();
		}
		this.handlers.click.activate();
		this.handlers.hover.activate();
		if (this.zoomBoxEnabled) {
			this.zoomBox.activate();
		}
		if (this.map.defaultCursor) {
			this.map.layerContainerDiv.style.cursor = this.map.defaultCursor;
		} else {
			this.map.layerContainerDiv.style.cursor = "url("+OpenLayers.Util.getRootPath() + "img/Pan.cur),default";
		}

		return OpenLayers.Control.prototype.activate.apply(
				this, arguments);
	},

	/**
	 * Method: draw
	 */
	draw : function() {
		// disable right mouse context menu for support of right
		// click events
		if (this.handleRightClicks) {
			this.map.viewPortDiv.oncontextmenu = OpenLayers.Function.False;
		}

		var clickCallbacks = {
			// 相应鼠标直接点击查询
			'click' : this.click,
			'dblclick' : this.defaultDblClick,
			'dblrightclick' : this.defaultDblRightClick
		};
		var clickOptions = {
			'double' : true,
			'stopDouble' : true
		};
		this.handlers.click = new OpenLayers.Handler.Click(
				this, clickCallbacks, clickOptions);

		this.handlers.hover = new OpenLayers.Handler.Hover(
				this, {
					pause : this.MouseHover
				}, {
					keyMask : this.keyMask
				});

		this.dragPan = new OpenLayers.Control.DragPan(
				OpenLayers.Util.extend({
					map : this.map,
					documentDrag : this.documentDrag
				}, this.dragPanOptions));
		this.zoomBox = new OpenLayers.Control.ZoomBox({
			map : this.map,
			keyMask : this.zoomBoxKeyMask
		});
		this.dragPan.draw();
		this.zoomBox.draw();
		this.handlers.wheel = new OpenLayers.Handler.MouseWheel(
				this, {
					"up" : this.wheelUp,
					"down" : this.wheelDown
				}, this.mouseWheelOptions);
	},

	/**
	 * Method: click
	 */
	click : function(evt) {
		
	},

	/**
	 * Method: deactivate
	 */
	deactivate : function() {
		this.zoomBox.deactivate();
		this.dragPan.deactivate();
		this.handlers.click.deactivate();
		this.handlers.hover.deactivate();
		this.handlers.wheel.deactivate();
		return OpenLayers.Control.prototype.deactivate.apply(
				this, arguments);
	},

	MouseHover : function(evt) {
		//this.poiHover.questPoiByBounds(evt);
	},

	CLASS_NAME : "OpenLayers.Control.DragPanControl"
});

var flag = true;
/**
 * Class: OpenLayers.Control.AddPOI 标注控件
 * 
 * 继承自: - <OpenLayers.Control>
 */
OpenLayers.Control.AddPOI = OpenLayers.Class(OpenLayers.Control, {

	/**
	 * Property: title {String} 工具按钮提示文字
	 */
	title : '添加标注',

	/**
	 * Property: type {String} 工具类型
	 */
	type : OpenLayers.Control.TYPE_TOOL,

	// 暂时不用，用全局的popup变量
	popup : null,

	/**
	 * Method: activate 控件被触发时设置鼠标手势
	 */
	activate : function() {
		this.map.labelLayer?this.map.labelLayer.clear():false;
		if (!this.map.markerLayer) {
			this.map.markerLayer = new OpenLayers.Layer.Markers("标注层");
			this.map.addLayer(this.map.markerLayer);
			this.map.markerLayer
					.setZIndex(this.map.Z_INDEX_BASE["Popup"] + 400);
			this.map.markerLayer.div.style.cursor = "pointer";
		}
		OpenLayers.Control.prototype.activate.apply(this, arguments);
		this.map.layerContainerDiv.style.cursor = "url("
				+ AT21.WebGIS.getAT21RootLocation() + "img/" + "AddPoi.cur)";
	},

	/**
	 * Method: draw 当控件加至地图时触发，创建Click类型的Handler
	 */
	draw : function() {
		if (typeof (addPoiPopup) != 'undefined') {
			this.handler = new OpenLayers.Handler.Click(this, {
				"click" : addPoiPopup
			});
		} else {
			this.handler = new OpenLayers.Handler.Click(this, {
				"click" : this.createPopup
			});
		}

	},

	/**
	 * Method: panMapDone 响应鼠标点击事件，弹出POI输入窗口
	 * 
	 * Parameters: xy - {<OpenLayers.Pixel>} 鼠标所在位置的像素坐标
	 */
	createPopup : function(evt) {
		var lonlat = this.map.getLonLatFromPixel(evt.xy);
		var icon = this.createIcon(null, null, null);
		var marker = new OpenLayers.Marker(lonlat, icon);
		if (this.afterCreatePopup(marker) != false) {
			this.map.markerLayer.addMarker(marker);
		}
		this.deactivate();
	},

	/**
	 * 创建icon对象
	 */
	createIcon : function(url, size, iconOffset) {
		// 如果icon地址为空的话给一个默认的图标
		if (url == null || url == "") {
			url = AT21.WebGIS.getAT21RootPath()
					+ '/plugins/21at-webgis/img/purple.png';
		}
		if (size == null) {
			size = new OpenLayers.Size(25, 25);
		}
		var offset = iconOffset == null ? new OpenLayers.Pixel(-(size.w / 2),
				-size.h) : iconOffset;
		var icon = new OpenLayers.Icon(url, size, offset);
		return icon;
	},

	afterCreatePopup : function(marker) {

	},

	CLASS_NAME : "OpenLayers.Control.AddPOI"

});

// ================================================
// buttons:
// ================================================

/**
 * Class: OpenLayers.Control.ClearSelection 清除控件
 * 
 * 继承自: - <OpenLayers.Control.Button>
 */
OpenLayers.Control.ClearSelection = OpenLayers.Class(OpenLayers.Control.Button,{

	/**
	 * Property: title {String} 工具按钮提示文字
	 */
	title : '清除地图',

	/**
	 * Property: EVENT_TYPES {String} 加入地图清除后事件
	 */

	EVENT_TYPES : [ "activate", "deactivate", "mapCleared" ],

	/**
	 * Method: trigger 控件被触发时清除地图表层内容（图形和文字），一般用于清除量算和选择后的高亮效果
	 */
	trigger : function() {
		this.map.defaultVLayer?this.map.defaultVLayer.destroyFeatures(): false;
		for (var i = 0; i < this.map.controls.length; i++) {
			var handler = this.map.controls[i].handler;
			if (handler && handler.destroyFeature) {
				this.map.controls[i].handler.destroyFeature();
			}
			if(handler && handler.layer){
				handler.layer.destroyFeatures();
			}
			if(this.map.controls[i].layer){
                if(this.map.controls[i].layer.destroyFeatures) {
                    this.map.controls[i].layer.destroyFeatures();
                }
			}
		}
		this.map.labelLayer?this.map.labelLayer.clear(): false;
		this.events.triggerEvent("mapCleared");
		if (this.map.markerLayer) {
			this.map.markerLayer.clearMarkers();
		}
	},

	CLASS_NAME : "OpenLayers.Control.ClearSelection"

});

/**
 * Class: OpenLayers.Control.SaveMap 地图输出控件
 * 
 * 继承自: - <OpenLayers.Control.Button>
 */
OpenLayers.Control.SaveMap = OpenLayers.Class(OpenLayers.Control.Button, {

	/**
	 * Property: title {String} 工具按钮提示文字
	 */
	title : '保存地图',
	
	url: null,

	/**
	 * Method: trigger 控件被触发时打开新窗口输出当前视窗下的地图
	 */
	trigger : function() {
		// alert(this.map.div.innerHTML);
		var aWin;
		var url = this.url || OpenLayers._getScriptLocation() + "mapprint.html";
		aWin = window.open(url, "地图打印", "");
		// 此处不严谨，还需要考虑TiledMap的情况
		// var wmsLayers = this.map.getLayersByClass("OpenLayers.Layer.WMS");
		// var tilewmslayers =
		// this.map.getLayersByClass("OpenLayers.Layer.TileWMS");
		// wmsLayers = wmsLayers.concat(tilewmslayers);
		// for(var i=0; i< wmsLayers.length; i++){
		// aWin.document.write("<div
		// style='position:absolute;left:10px;top:10px;'><img src='" +
		// this.getMapUrl(wmsLayers[i]) + "'></div>");
		var mapdiv = $(this.map.div);
		var html = mapdiv.html();
		var map = this.map;
		//window.map = this.map;
		window.printw = map.size.w+"px";
		window.printh = map.size.h+"px";
		window.printcont = "<div style='width:" + map.size.w + "px; height:"
		+ map.size.h + "px; overflow: hidden;position: relative;'>" + html
		+ "</div>";
//		if (!jQuery.browser.msie) {
//			window.setTimeout(function() {
//				var wrapper = jQuery("<div style='width:" + map.size.w
//						+ "px; height:" + map.size.h
//						+ "px; overflow: hidden; position: relative;'></div>");
//				wrapper.append(mapdiv.clone());
//				$(aWin.document.body).find("#wrapper").width(map.size.w)
//						.height(map.size.h).append(wrapper);
//			}, 500);
//		} else {
//			$(aWin.document.body).find("#wrapper").width(map.size.w).height(
//					map.size.h).html(
//					"<div style='width:" + map.size.w + "px; height:"
//							+ map.size.h + "px; overflow: hidden;position: relative;'>" + html
//							+ "</div>");
//		}
//		// }
//		aWin.document.close();
//		aWin.focus();
	},

	/**
	 * Method: getMapUrl 获取地图图片的url
	 * 
	 * Parameters: wmsLayer - {<OpenLayers.Layer.WMS>} WMS图层对象
	 */
	getMapUrl : function(wmsLayer) {
		var newParams = {
			'BBOX' : wmsLayer.encodeBBOX ? wmsLayer.map.getExtent().toBBOX()
					: wmsLayer.map.getExtent().toArray(),
			'WIDTH' : wmsLayer.map.size.w,
			'HEIGHT' : wmsLayer.map.size.h
		};
		var requestString = wmsLayer.getFullRequestString(newParams);
		return requestString;
	},

	CLASS_NAME : "OpenLayers.Control.SaveMap"

});

/**
 * Class: OpenLayers.Control.PrintMap 地图打印控件
 * 
 * 继承自: - <OpenLayers.Control.SaveMap>
 */
OpenLayers.Control.PrintMap = OpenLayers.Class(OpenLayers.Control.SaveMap,{
	/**
	 * Property: title {String} 工具按钮提示文字
	 */
	title : '打印地图',

	/**
	 * Method: trigger 控件被触发时打开新窗口打印当前视窗下的地图
	 */
	trigger : function() {
		var aWin;
		aWin = window.open("", "打印地图", "");
		aWin.document.write("<html>");
		aWin.document.write("<head>");
		aWin.document.write("<script>");

		aWin.document.write("function testA(){alert('haha');}");
		aWin.document.write("</script>");
		aWin.document.write("</head>");
		aWin.document.write("<body onload=''>");
		// aWin.document.write("<div
		// style='position:absolute;left:10px;top:10px;width:"+this.map.size.w+";height:"+this.map.size.h+"'>");
		// clip:rect(
		aWin.document
				.write("<div style='position:absolute;left:0px;top:0px;clip:rect(10px "
						+ this.map.div.currentStyle.width
						+ " "
						+ this.map.div.currentStyle.height
						+ " 10px)'>");
		aWin.document
				.write(this.map.layerContainerDiv.innerHTML);
		aWin.document.write("</div>");
		aWin.document.write("</body>");
		aWin.document.write("</html>");
		aWin.document.close();
		aWin.print();
	},

	CLASS_NAME : "OpenLayers.Control.PrintMap"

});

/**
 * Class: OpenLayers.Control.SwitchOverview 鹰眼切换控件
 * 
 * 继承自: - <OpenLayers.Control.Button>
 */
OpenLayers.Control.SwitchOverview = OpenLayers.Class(OpenLayers.Control.Button,{
	/**
	 * Property: title {String} 工具按钮提示文字
	 */
	title : '鹰眼控制',

	/**
	 * Method: trigger 控件被触发时切换鹰眼的显示和隐藏
	 */
	trigger : function() {
		// alert("developing...");
		// 尚未考虑在地图界外的情况
		var ctrlClassName = "OpenLayers.Control.Overview";
		var controls = this.map
				.getControlsByClass(ctrlClassName);
		if (!controls || !controls[0]) {
			alert(" 找不到鹰眼控件！ ");
			return;
		}
		if (this.map.getLayersByClass("OpenLayers.Layer.WMS").length == 0) {
			alert("地图中至少存在一个wms图层鹰眼图才能正常显示！");
			return;
		}
		var ovControl = controls[0];
		// alert(ovControl.element.style.display);
		if (ovControl.element.style.display == '') {
			ovControl.minimizeControl();
		} else {
			ovControl.maximizeControl();
		}

	},

	CLASS_NAME : "OpenLayers.Control.SwitchOverview"

});

/**
 * Class: OpenLayers.Control.SwitchLayer 图层控制切换控件
 * 
 * 继承自: - <OpenLayers.Control.Button>
 */
OpenLayers.Control.SwitchLayer = OpenLayers.Class(OpenLayers.Control.Button, {

	/**
	 * Property: title {String} 工具按钮提示文字
	 */
	title : '图层控制',

	/**
	 * Method: trigger 控件被触发时切换图层控制的显示和隐藏
	 */
	trigger : function() {
		// alert("developing...");

		// 尚未考虑在地图界外的情况
		var ctrlClassName = "OpenLayers.Control.LayerControlGrid";
		var controls = this.map.getControlsByClass(ctrlClassName);
		if (!controls || !controls[0]) {
			alert(" 找不到图层控制控件！ ");
			return;
		}
		var layerControl = controls[0];
		if (layerControl.floatDiv.display) {
			layerControl.minimizeControl();
		} else {
			layerControl.maximizeControl();
		}

	},

	CLASS_NAME : "OpenLayers.Control.SwitchLayer"

});

/**
 * Class: OpenLayers.Control.SetMultiMap 多地图设置控件
 * 
 * 继承自: - <OpenLayers.Control.Button>
 */
OpenLayers.Control.SetMultiMap = OpenLayers.Class(OpenLayers.Control.Button, {

	/**
	 * Property: title {String} 工具按钮提示文字
	 */
	title : '设置联动',

	/**
	 * Method: draw 创建设置面板DIV
	 */
	draw : function() {

		OpenLayers.Control.prototype.draw.apply(this, arguments);

		// 屏蔽双击
		OpenLayers.Event.observe(this.div, "mouseup", OpenLayers.Function
				.bindAsEventListener(OpenLayers.Event.stop));
		OpenLayers.Event.observe(this.div, "click", OpenLayers.Function
				.bindAsEventListener(OpenLayers.Event.stop));
		OpenLayers.Event.observe(this.div, "mousedown", OpenLayers.Function
				.bindAsEventListener(OpenLayers.Event.stop));
		OpenLayers.Event.observe(this.div, "rightclick", OpenLayers.Function
				.bindAsEventListener(OpenLayers.Event.stop));
		OpenLayers.Event.observe(this.div, "dblclick", OpenLayers.Function
				.bindAsEventListener(OpenLayers.Event.stop));

		this.div.style.display = "none";
		return this.div;

	},

	/**
	 * Method: redraw 刷新设置面板DIV
	 */
	redraw : function() {
		this.div.innerHTML = "";
		for ( var i = 0, len = multiMap.maps.length; i < len; i++) {

			var map = multiMap.maps[i];

			var checked = (map.bindCode == this.map.bindCode);
			// radio
			var inputElem = document.createElement("input");
			inputElem.id = "input_" + map.id;
			inputElem.name = "input_" + this.map.id;
			inputElem.type = "checkbox";
			inputElem.value = map.bindCode;
			inputElem.checked = checked;
			inputElem.defaultChecked = checked;
			if (map.div.id == this.map.div.id) {
				inputElem.disabled = true;
			}

			// text
			var labelSpan = document.createElement("span");
			labelSpan.innerHTML = "地图" + (i + 1); // map.id; //显示由ID改为序号

			// line break
			var br = document.createElement("br");

			var context = {
				'inputElem' : inputElem,
				'control' : this,
				'map' : map,
				'bindCode' : map.bindCode
			};
			OpenLayers.Event.observe(inputElem, "mouseup", OpenLayers.Function
					.bindAsEventListener(this.onInputClick, context));

			this.div.appendChild(inputElem);
			this.div.appendChild(labelSpan);
			this.div.appendChild(br);
		}

		var closeBtn = document.createElement("input");
		closeBtn.id = "input_btn";
		closeBtn.name = "input_btn_" + this.map.id;
		closeBtn.type = "button";
		closeBtn.value = "确定";
		var context = {
			'inputElem' : inputElem,
			'control' : this
		};
		OpenLayers.Event.observe(closeBtn, "click", OpenLayers.Function
				.bindAsEventListener(this.submit, context));
		closeBtn.style.backgroundPositionX = "center";

		// line break
		var br = document.createElement("br");
		this.div.appendChild(closeBtn);
		this.div.appendChild(br);

	},

	/**
	 * Method: trigger 控件被触发时切换设置面板的显示和隐藏
	 */
	trigger : function() {
		this.redraw();
		this.div.style.display = (this.div.style.display == "") ? "none" : "";
	},

	/**
	 * Method: onInputClick 响应checkbox点击事件
	 */
	onInputClick : function(e) {
		this.inputElem.checked = !this.inputElem.checked;

		OpenLayers.Event.stop(e);
	},

	/**
	 * Method: submit 提交设置
	 */
	submit : function(e) {
		this.control.div.style.display = "none";

		// getElementsByTagName("INPUT"); getElementsByName("input_" +
		// this.control.map.id); childNodes
		var chkboxs = this.control.div.getElementsByTagName("INPUT");

		// 重设绑定规则
		var newCode = OpenLayers.Util.createUniqueID(0);
		for ( var i = 0; i < chkboxs.length - 1; i++) {
			if (chkboxs[i].checked) { // 勾选的情况
				multiMap.maps[i].bindCode = this.control.map.bindCode;
			} else if (multiMap.maps[i].bindCode == this.control.map.bindCode) {// 让原绑定地图另立门户
				multiMap.maps[i].bindCode = newCode;
			}
		}

		// 重新绑定
		multiMap.rebind();
	},

	CLASS_NAME : "OpenLayers.Control.SetMultiMap"

});